package luzhin.frames;

import java.io.*;
import java.awt.event.*;
import javax.swing.*;

import luzhin.*;

/**
 * Controller for a button frame.
 * @author lacungus
 *
 */
public class ButtonFrameController implements AbstractMainFrameController, ActionListener {
	private ButtonFrame frame; 
	
	public ButtonFrameController() {		
	}
	
	public void setFrame(MainFrame frame) {
		this.frame = (ButtonFrame)frame;
		for (JButton button : this.frame.allButtons)
			button.addActionListener(this);
		this.frame.saveItem.addActionListener(this);
	}
	
	private JButton firstPushedButton = null;
	private JButton secondPushedButton = null;
	private volatile int amPushedButtons = 0;
	
	// save game button is pushed
	private void saveGame() {
		JFileChooser fc = new JFileChooser();
		fc.setCurrentDirectory(new File("."));
        int returnVal = fc.showSaveDialog(frame);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            try {
            	frame.game.getBoard().save(file.getAbsolutePath());
            } catch (IOException e) {
            	e.printStackTrace();
            }
        } else {
        }
	}
	
	/**
	 * One of the buttons with chess pieces was pushed.
	 */	
	public void actionPerformed(ActionEvent event) {
		if (event.getSource().getClass().toString().equals("class javax.swing.JMenuItem")) {
			JMenuItem menuItem = (JMenuItem)event.getSource();
			if (menuItem.getName().equals("Save")) {
				saveGame();
				return;
			}
			return;
		}
		JButton pushedButton = (JButton) event.getSource();
		if (amPushedButtons == 0) {
			// A button was pushed for the first time - the starting point of the new move.
			firstPushedButton = pushedButton;
			amPushedButtons = 1;
			return;
		}
		if (amPushedButtons == 1) {
			// A button was pushed for the second time - time to move.
			secondPushedButton = pushedButton;
			if (secondPushedButton.equals(firstPushedButton)) {
				// cancel move
				amPushedButtons = 0;
				return;
			}
			amPushedButtons = 2;
			return;
		}
	}

	/**
	 * @return Move made by the user.
	 */
	public Move getMove() {
		amPushedButtons = 0;
		while (amPushedButtons != 2) {		
		}
		String moveString = firstPushedButton.getName() + secondPushedButton.getName();
		
		firstPushedButton = null;
		secondPushedButton = null;
		Move move = new Move(moveString);
		return move;
	}
	
	public void drawGame(Game game) {
		frame.drawGame(game);
	}
	
	public void redraw(Game game) {
		frame.redraw(game);
	}	
}
